from datetime import datetime
import hashlib
import random

from django.db import models


# Create your models here.

def sub(key, m_user):
    key = str(key).strip()
    obj = SecretKeys.objects.get(key=key)
    print(obj)
    if not obj or obj.num <= 0:
        return False
    obj.m_user = str(m_user).strip()
    obj.num -= 1
    obj.save()
    return True


def hash_key():
    data = str(datetime.now()) + str(random.random())
    sha2 = hashlib.sha256(data.encode('utf-8')).hexdigest()
    return sha2


class SecretKeys(models.Model):
    key_name = models.CharField('序号', max_length=256)
    key = models.CharField('序列', max_length=256, default=hash_key)
    c_user = models.CharField('创建者', max_length=24, default='2020244004')
    m_user = models.CharField('最近修改者', max_length=24, default='2020244004')
    num = models.IntegerField('剩余次数', default='50')
    c_time = models.DateTimeField('创建时间', auto_now_add=True)
    m_time = models.DateTimeField('修改时间', auto_now=True)

    class Meta:
        db_table = 'secret_keys'
        verbose_name = '秘钥'
        verbose_name_plural = '秘钥'

    def __str__(self):
        return self.key
